<%@ page import="java.sql.*" %>
<%@ page import="com.study.entity.User" %>
<%--
  Created by IntelliJ IDEA.
  User: WS
  Date: 2020/2/26
  Time: 10:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
<jsp:useBean id="user" class="com.study.entity.User" scope="page"></jsp:useBean>
<jsp:setProperty name="user" property="*"></jsp:setProperty>
<%
    String msg = "";
    String url = "jdbc:mysql://localhost:3306/servletdemo?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true";
    String userName = "root";
    String password = "123456";
    Class.forName("com.mysql.jdbc.Driver");
    // 建立连接
    Connection conn = DriverManager.getConnection(url, userName, password);
    String sql = "select * from tab_user where name=? and pwd=?";
    PreparedStatement statement = conn.prepareStatement(sql);
    statement.setString(1, user.getName());
    statement.setString(2, user.getPwd());
    try {
        ResultSet resultSet = statement.executeQuery();
        if (resultSet.next()) {
            user = new User();
            user.setAge(resultSet.getInt("age"));
            user.setBirthday(resultSet.getDate("birthday"));
            user.setDetail(resultSet.getString("detail"));
            user.setEmail(resultSet.getString("email"));
            user.setId(resultSet.getString("id"));
            user.setName(resultSet.getString("name"));
            user.setPwd(resultSet.getString("pwd"));
            user.setSex(resultSet.getInt("sex"));
        } else {
            user = null;
        }
        resultSet.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        statement.close();
        conn.close();
    }
    if (user != null) {
        request.removeAttribute("msg");
        request.getSession().setAttribute("user", user);
        request.getRequestDispatcher("index.jsp").forward(request, response);
    } else {
        request.setAttribute("msg", "用户名或密码错误");
        request.getRequestDispatcher("login.jsp").forward(request, response);

    }
%>
</body>
</html>
